import React, { useState, useRef, useEffect } from 'react'
import {
  Card,
  Input,
  Button,
  List,
  Avatar,
  Typography,
  Space,
  Divider,
  Tag,
  Empty,
  Spin,
  message,
  Tooltip,
  Row,
  Col,
  Drawer,
  Badge
} from 'antd'
import {
  SendOutlined,
  StopOutlined,
  UserOutlined,
  RobotOutlined,
  ClearOutlined,
  HistoryOutlined,
  MessageOutlined,
  ToolOutlined,
  BulbOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  PlusOutlined
} from '@ant-design/icons'
import type { ElectronAPI, HistorySessionInfo, ChatMessage } from '../electron-types'
import { createIPCService } from '../services/ipc-service'

const { TextArea } = Input
const { Text, Paragraph } = Typography

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  reasoning?: string  // 改为reasoning字段
  timestamp: Date
  loading?: boolean
}

interface ChatInterfaceProps {
  electronAPI: ElectronAPI | null
}

// 添加接口来描述历史结果的格式
interface ChatHistoryResult {
  success?: boolean;
  messages?: ChatMessage[];
}

export const ChatInterface: React.FC<ChatInterfaceProps> = ({ electronAPI }) => {
  // 创建IPC服务实例
  const ipcService = electronAPI ? createIPCService(electronAPI) : null;
  
  const [messages, setMessages] = useState<Message[]>([])
  const [inputValue, setInputValue] = useState('')
  const [loading, setLoading] = useState(false)
  const [currentContent, setCurrentContent] = useState('')
  const [isToolExecuting, setIsToolExecuting] = useState(false)
  const [currentToolName, setCurrentToolName] = useState('')
  const [currentReasoning, setCurrentReasoning] = useState('')
  const [isReasoning, setIsReasoning] = useState(false)
  const [showReasoning, setShowReasoning] = useState(true)
  // 新增历史相关状态
  const [historyVisible, setHistoryVisible] = useState(false)
  const [historyList, setHistoryList] = useState<HistorySessionInfo[]>([])
  const [historyLoading, setHistoryLoading] = useState(false)
  const [sessionLoading, setSessionLoading] = useState(false)
  // 新建会话状态
  const [newSessionLoading, setNewSessionLoading] = useState(false)
  const listRef = useRef<HTMLDivElement>(null)

  // 滚动到底部
  const scrollToBottom = () => {
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight
    }
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages, currentContent, currentReasoning])

  // 设置AI流式响应监听器
  useEffect(() => {
    if (!ipcService) return

    // 流开始
    const handleStreamStart = () => {
      setLoading(true)
      setCurrentContent('')
      setCurrentReasoning('')
      setIsReasoning(false)
      console.log('AI流开始')
    }

    // 流内容
    const handleStreamContent = (data: { content: string }) => {
      setCurrentContent(prev => prev + data.content)
    }

    // 流结束
    const handleStreamComplete = async () => {
      console.log('AI流结束')
      setLoading(false)
      
      // 清空当前流式内容
      setCurrentContent('')
      setCurrentReasoning('')
      setIsReasoning(false)
      
      // 从后端获取完整的消息列表
      try {
        const historyResult = await ipcService.getChatHistory() as ChatHistoryResult;
        if (historyResult && historyResult.success && Array.isArray(historyResult.messages)) {
          // 转换消息格式并更新状态
          const formattedMessages = historyResult.messages
            .filter((msg: ChatMessage) => msg.role === 'user' || msg.role === 'assistant')
            .map((msg: ChatMessage, index: number) => ({
              id: `msg_${index}_${Date.now()}`,
              role: msg.role as 'user' | 'assistant',
              content: msg.content,
              reasoning: msg.reasoning,
              timestamp: new Date()
            }))
          
          setMessages(formattedMessages)
          console.log('消息列表已从后端同步更新')
        } else {
          console.error('获取消息历史失败:', historyResult)
        }
      } catch (error) {
        console.error('获取消息历史时出错:', error)
      }
    }

    // 工具执行开始
    const handleToolStart = (data: { toolName: string, args: any }) => {
      setIsToolExecuting(true)
      setCurrentToolName(data.toolName)
      console.log('工具执行开始:', data.toolName)
    }

      // 工具执行完成
      const handleToolComplete = (data: { toolName: string, result: string }) => {
        setIsToolExecuting(false)
        setCurrentToolName('')
        console.log('工具执行完成:', data.toolName)
      }

      // 思考过程开始
      const handleReasoning = (data: { reasoning: string }) => {
        setIsReasoning(true)
        setCurrentReasoning(prev => prev + data.reasoning)
      }

      // 思考过程结束
      const handleReasoningEnd = () => {
        setIsReasoning(false)
        console.log('思考过程结束')
      }

      // 错误处理
      const handleError = (data: { error: Error }) => {
        setLoading(false)
        setIsToolExecuting(false)
        setIsReasoning(false)
        message.error('AI响应错误: ' + data.error.message)
        console.error('AI错误:', data.error)
      }

    // 注册事件监听器
    if (ipcService) {
      ipcService.onAiStreamStart(handleStreamStart)
      ipcService.onAiStreamContent(handleStreamContent)
      ipcService.onAiStreamComplete(handleStreamComplete)
      ipcService.onAiReasoning(handleReasoning)
      ipcService.onAiReasoningEnd(handleReasoningEnd)
      ipcService.onAiToolExecutionStart(handleToolStart)
      ipcService.onAiToolExecutionComplete(handleToolComplete)
      ipcService.onAiError(handleError)
    }

    // 清理函数
    return () => {
      if (ipcService) {
        ipcService.removeAllListeners()
      }
    }
  }, [ipcService, currentContent])

  // 处理键盘按键事件
  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      if (loading || isToolExecuting) {
        handleAbort()
      } else {
        sendMessage()
      }
    }
    // 添加Escape键取消
    if (e.key === 'Escape' && (loading || isToolExecuting)) {
      e.preventDefault()
      handleAbort()
    }
  }

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim() || loading || !ipcService) return

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputValue.trim(),
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')

    try {
      console.log('发送AI聊天请求:', inputValue.trim())
      
      // 调用真正的AI聊天IPC - 使用装饰器服务
      if (ipcService) {
        await ipcService.aiChat(inputValue.trim())
      } else {
        throw new Error('IPC服务不可用')
      }
      
    } catch (error) {
      message.error('发送失败: ' + error)
      console.error('Send message error:', error)
      resetChatState()
    }
  }

  // 重置聊天状态
  const resetChatState = () => {
    setLoading(false)
    setIsToolExecuting(false)
    setCurrentToolName('')
    setCurrentContent('')
    setCurrentReasoning('')
    setIsReasoning(false)
  }

  // 取消当前请求
  const handleAbort = async () => {
    try {
      if (ipcService) {
        await ipcService.abortChat()
        message.info('已取消当前请求')
      }
      // 重置状态
      resetChatState()
    } catch (error) {
      message.error('取消失败: ' + error)
      console.error('Abort error:', error)
    }
  }

  // 清空对话
  const clearMessages = async () => {
    try {
      if (ipcService) {
        await ipcService.clearChatHistory()
      }
      setMessages([])
      resetChatState()
      message.info('对话已清空')
    } catch (error) {
      message.error('清空失败: ' + error)
    }
  }

  // 新建会话
  const createNewSession = async () => {
    if (!ipcService) {
      message.error('IPC服务不可用')
      return
    }

    // 如果当前有对话内容，询问是否保存
    if (messages.length > 0) {
      // 这里可以添加确认对话框，暂时直接创建新会话
      console.log('当前有对话内容，将自动保存到历史记录')
    }

    try {
      setNewSessionLoading(true)
      
      // 清空前端状态
      setMessages([])
      setCurrentContent('')
      setCurrentReasoning('')
      setIsReasoning(false)
      setIsToolExecuting(false)
      setCurrentToolName('')
      setLoading(false)
      
      // 清空后端聊天历史，开始新会话
      await ipcService.clearChatHistory()
      
      message.success('新会话已创建')
      console.log('✅ 新会话创建成功')
      
    } catch (error) {
      message.error('创建新会话失败: ' + error)
      console.error('❌ 创建新会话失败:', error)
    } finally {
      setNewSessionLoading(false)
    }
  }

  // 关闭历史侧边栏
  const handleHistoryClose = () => {
    setHistoryVisible(false)
  }

  // 格式化时间
  const formatTime = (timestamp: number | string) => {
    const date = new Date(timestamp)
    return date.toLocaleString()
  }

  // 处理查看历史
  const handleHistoryClick = async () => {
    if (!ipcService) {
      message.error('IPC服务不可用')
      return
    }

    try {
      setHistoryLoading(true)
      // 获取历史会话列表
      if (ipcService) {
        const historyList = await ipcService.getHistoryList()
        setHistoryList(historyList)
        setHistoryVisible(true)
      } else {
        throw new Error('IPC服务不可用')
      }
    } catch (error) {
      message.error('获取历史失败: ' + error)
    } finally {
      setHistoryLoading(false)
    }
  }

  // 加载特定会话到聊天界面
  const handleLoadSession = async (sessionId: string) => {
    if (!ipcService) {
      message.error('IPC服务不可用')
      return
    }

    try {
      setSessionLoading(true)
      // 加载会话到当前聊天
      const result = await ipcService.loadSessionToChat(sessionId)
      
      if (result.success) {
        message.success(`已加载历史会话 (${result.messageCount} 条消息)`)
        setHistoryVisible(false) // 关闭侧边栏
        
        // 清空当前显示的消息和状态
        setMessages([])
        setCurrentContent('')
        setCurrentReasoning('')
        setIsReasoning(false)
        setIsToolExecuting(false)
        setCurrentToolName('')
        setLoading(false)
        
        // 获取加载的历史消息并显示
        try {
          const historyResult = await ipcService.getChatHistory() as ChatHistoryResult;
          if (historyResult && historyResult.success && Array.isArray(historyResult.messages)) {
              // 转换历史消息格式并设置到状态中
              const formattedMessages = historyResult.messages
                .filter((msg: ChatMessage) => msg.role === 'user' || msg.role === 'assistant') // 只保留用户和助手消息
                .map((msg: ChatMessage, index: number) => ({
                  id: `history_${index}_${Date.now()}`,
                  role: msg.role as 'user' | 'assistant',
                  content: msg.content,
                  reasoning: msg.reasoning, // 包含历史消息的reasoning内容
                  timestamp: new Date()
                }))
            
            setMessages(formattedMessages)
            message.info(`历史会话已加载完成 (${formattedMessages.length} 条消息)，您可以继续对话`)
          } else {
            console.warn('历史消息格式不正确:', historyResult)
            message.info('历史会话已加载完成，您可以继续对话')
          }
        } catch (historyError) {
          console.warn('获取历史消息失败:', historyError)
          message.info('历史会话已加载完成，您可以继续对话')
        }
      }
    } catch (error) {
      message.error('加载会话失败: ' + error)
    } finally {
      setSessionLoading(false)
    }
  }

  // 渲染消息的组件
  const renderMessage = (msg: Message) => (
    <List.Item style={{ border: 'none', padding: '12px 0' }}>
      <List.Item.Meta
        avatar={
          <Avatar 
            icon={msg.role === 'user' ? <UserOutlined /> : <RobotOutlined />} 
            style={{ 
              backgroundColor: msg.role === 'user' ? '#1890ff' : '#52c41a'
            }}
          />
        }
        title={
          <Space>
            <Text strong>
              {msg.role === 'user' ? '用户' : 'AI助手'}
            </Text>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {msg.timestamp.toLocaleTimeString()}
            </Text>
          </Space>
        }
          description={
            <div>
              {/* 推理过程 - 仅为AI消息显示 */}
              {msg.role === 'assistant' && msg.reasoning && showReasoning && (
                <div style={{ 
                  backgroundColor: '#fffbe6',
                  padding: '12px',
                  borderRadius: '8px',
                  marginTop: '8px',
                  marginBottom: '8px',
                  border: '1px solid #ffe58f'
                }}>
                  <div style={{ marginBottom: '8px' }}>
                    <BulbOutlined style={{ color: '#faad14', marginRight: '6px' }} />
                    <Text strong style={{ color: '#faad14', fontSize: '12px' }}>推理过程</Text>
                  </div>
                  <Paragraph style={{ 
                    margin: 0, 
                    whiteSpace: 'pre-wrap',
                    fontStyle: 'italic',
                    fontSize: '13px',
                    color: '#8c8c8c'
                  }}>
                    {msg.reasoning}
                  </Paragraph>
                </div>
              )}
            
            {/* 回复内容 */}
            <div style={{ 
              backgroundColor: msg.role === 'user' ? '#e6f7ff' : '#f6ffed',
              padding: '12px',
              borderRadius: '8px',
              marginTop: '8px',
              border: `1px solid ${msg.role === 'user' ? '#91d5ff' : '#b7eb8f'}`
            }}>
              <Paragraph 
                style={{ 
                  margin: 0, 
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-word'
                }}
              >
                {msg.content}
              </Paragraph>
            </div>
          </div>
        }
      />
    </List.Item>
  )

  return (
    <>
      <Card
      title={
        <Space>
          <MessageOutlined />
          <span>AI对话界面</span>
          <Tag color="blue">{messages.length} 条消息</Tag>
          {isToolExecuting && (
            <Tag color="orange" icon={<ToolOutlined />}>
              执行工具: {currentToolName}
            </Tag>
          )}
        </Space>
      }
      extra={
        <Space>
            <Tooltip title={showReasoning ? "隐藏推理过程" : "显示推理过程"}>
              <Button 
                type="text" 
                icon={showReasoning ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                onClick={() => setShowReasoning(!showReasoning)}
              />
            </Tooltip>
          <Tooltip title="查看历史">
            <Button 
              type="text" 
              icon={<HistoryOutlined />}
              onClick={handleHistoryClick}
              loading={historyLoading}
            />
          </Tooltip>
          <Tooltip title="清空对话">
            <Button 
              type="text" 
              icon={<ClearOutlined />} 
              onClick={clearMessages}
              disabled={messages.length === 0 && !currentContent}
            />
          </Tooltip>
          <Tooltip title="新建会话">
            <Button 
              type="text" 
              icon={<PlusOutlined />} 
              onClick={createNewSession}
              loading={newSessionLoading}
              disabled={loading || isToolExecuting || sessionLoading}
            />
          </Tooltip>
        </Space>
      }
      style={{ height: '600px', display: 'flex', flexDirection: 'column' }}
      bodyStyle={{ 
        flex: 1, 
        display: 'flex', 
        flexDirection: 'column',
        padding: 0
      }}
    >
      {/* 消息列表区域 */}
      <div 
        ref={listRef}
        style={{ 
          flex: 1, 
          overflowY: 'auto', 
          padding: '0 24px',
          maxHeight: '400px'
        }}
      >
        {messages.length === 0 && !currentContent ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="开始您的AI对话吧!"
            style={{ 
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
              height: '100%'
            }}
          />
        ) : (
          <List
            dataSource={messages}
            renderItem={renderMessage}
            split={false}
          />
        )}
        
        {/* 当前流式内容 */}
        {(loading || currentContent || isReasoning || currentReasoning) && (
          <List.Item style={{ border: 'none', padding: '12px 0' }}>
            <List.Item.Meta
              avatar={
                <Avatar 
                  icon={<RobotOutlined />}
                  style={{ backgroundColor: '#52c41a' }}
                />
              }
              title={
                <Space>
                  <Text strong>AI助手</Text>
                  {(loading || isReasoning) && <Spin size="small" />}
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {isReasoning ? '正在思考...' : loading ? '正在回复...' : '完成'}
                  </Text>
                </Space>
              }
              description={
                <div>
                  {/* 当前思考过程 */}
                  {(isReasoning || currentReasoning) && showReasoning && (
                    <div style={{ 
                      backgroundColor: '#fffbe6',
                      padding: '12px',
                      borderRadius: '8px',
                      marginTop: '8px',
                      marginBottom: currentContent ? '8px' : '0px',
                      border: '1px solid #ffe58f'
                    }}>
                      <div style={{ marginBottom: '8px' }}>
                        <BulbOutlined style={{ color: '#faad14', marginRight: '6px' }} />
                        <Text strong style={{ color: '#faad14', fontSize: '12px' }}>思考过程</Text>
                        {isReasoning && <Spin size="small" style={{ marginLeft: '8px' }} />}
                      </div>
                      <Paragraph style={{ 
                        margin: 0, 
                        whiteSpace: 'pre-wrap',
                        fontStyle: 'italic',
                        fontSize: '13px',
                        color: '#8c8c8c'
                      }}>
                        {currentReasoning || '准备开始思考...'}
                      </Paragraph>
                    </div>
                  )}
                  
                  {/* 当前回复内容 */}
                  {(loading || currentContent) && (
                    <div style={{ 
                      backgroundColor: '#f6ffed',
                      padding: '12px',
                      borderRadius: '8px',
                      marginTop: '8px',
                      border: '1px solid #b7eb8f'
                    }}>
                      <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                        {currentContent || '正在生成回复...'}
                      </Paragraph>
                    </div>
                  )}
                </div>
              }
            />
          </List.Item>
      )}
      </div>

      <Divider style={{ margin: '12px 0' }} />

      {/* 输入区域 */}
      <div style={{ padding: '0 24px 24px' }}>
        <Row gutter={[12, 12]}>
          <Col flex="auto">
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入您的问题... (Enter发送，Shift+Enter换行)"
              autoSize={{ minRows: 2, maxRows: 4 }}
              disabled={loading}
            />
          </Col>
            <Col>
              <Button
                type={loading || isToolExecuting ? "default" : "primary"}
                danger={loading || isToolExecuting}
                icon={loading || isToolExecuting ? <StopOutlined /> : <SendOutlined />}
                onClick={loading || isToolExecuting ? handleAbort : sendMessage}
                disabled={!loading && !isToolExecuting && !inputValue.trim()}
                style={{ height: '100%' }}
              >
                {loading || isToolExecuting ? '取消' : '发送'}
              </Button>
            </Col>
        </Row>
        
        {(loading || isToolExecuting) && (
          <div style={{ marginTop: '8px', textAlign: 'center' }}>
            <Space>
              <Spin size="small" />
              <Text type="secondary">
                {isToolExecuting ? `正在执行工具: ${currentToolName}` : 'AI正在思考中...'}
              </Text>
            </Space>
          </div>
        )}
        </div>
      </Card>

        {/* 历史消息侧边栏 */}
        <Drawer
          title={
            <Space>
              <HistoryOutlined />
              <span>历史会话</span>
              {historyList.length > 0 && (
                <Badge 
                  count={historyList.length} 
                  style={{ backgroundColor: '#52c41a' }}
                />
              )}
            </Space>
          }
          placement="left"
          onClose={handleHistoryClose}
          open={historyVisible}
          width={450}
          bodyStyle={{ padding: '16px' }}
        >
          {historyLoading ? (
            <div style={{ textAlign: 'center', padding: '50px 0' }}>
              <Spin size="large" />
              <div style={{ marginTop: '16px' }}>
                <Text type="secondary">正在加载历史数据...</Text>
              </div>
            </div>
          ) : historyList.length > 0 ? (
            <div>
              {/* 统计信息 */}
              <Card size="small" style={{ marginBottom: '16px' }}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {historyList.length}
                  </div>
                  <div style={{ fontSize: '14px', color: '#666' }}>历史会话</div>
                </div>
              </Card>

              {/* 会话列表 */}
              <List
                dataSource={historyList}
                renderItem={(session) => (
                  <List.Item style={{ padding: '8px 0', border: 'none' }}>
                    <Card 
                      size="small" 
                      hoverable
                      style={{ width: '100%', cursor: 'pointer' }}
                      onClick={() => handleLoadSession(session.sessionId)}
                      loading={sessionLoading}
                    >
                      <div style={{ marginBottom: '8px' }}>
                        <Text strong style={{ fontSize: '14px' }}>
                          {session.title}
                        </Text>
                      </div>
                      
                      <div style={{ marginBottom: '8px' }}>
                        <Space split={<Divider type="vertical" />}>
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {formatTime(session.timestamp)}
                          </Text>
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {session.messageCount} 条消息
                          </Text>
                        </Space>
                      </div>
                      
                      <div style={{ fontSize: '11px', color: '#999' }}>
                        会话ID: {session.sessionId.substring(8, 16)}...
                      </div>
                    </Card>
                  </List.Item>
                )}
              />
            </div>
          ) : (
            <Empty 
              description="暂无历史会话"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Drawer>
    </>
  )
}